/**

 * Copyright (C) 2006-2016 湖南天天向上网络技术有限公司
 * 文件名：com..rrt.util.HttpClientUtils.java
 * 作  者：LF
 * 日  期：2014-11-27 下午05:43:08
 * 描  述：
 * 版  本：1.0
 */
package com.bskj.common.utils;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.SimpleHttpConnectionManager;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class HttpClientUtils {
	
	private static final org.apache.http.client.HttpClient httpClient;
	static {
		httpClient = new SSLClient();
	}

	/**
	 * http请求
	 * @param url
	 * @param params
	 * @return
	 */
	public static String postHttpAndHttps(String url, Map<String, String> params) {
		if (url.startsWith("https://")) {
			return doPost(url, params, "UTF-8");
		}
		if (url.startsWith("http://")) {
			return postRequest(url, params);
		}
		return "错误的请求地址";
	}

	/**
	 * HttpClient 模拟POST请求 方法说明
	 * 
	 * @Discription:扩展说明
	 * @param url
	 * @param params
	 * @return String
	 * @Author: feizi
	 * @Date: 2015年4月17日 下午7:15:59
	 * @ModifyUser：feizi
	 * @ModifyDate: 2015年4月17日 下午7:15:59
	 */
	public static String postRequest(String url, Map<String, String> params) {
		// 构造HttpClient的实例
		HttpClient httpClient = new HttpClient();

		// 创建POST方法的实例
		PostMethod postMethod = new PostMethod(url);

		// 设置请求头信息
		postMethod.setRequestHeader("Connection", "close");

		// 添加参数
		for (Map.Entry<String, String> entry : params.entrySet()) {
			postMethod.addParameter(entry.getKey(), entry.getValue().toString());
		}

		// 使用系统提供的默认的恢复策略,设置请求重试处理，用的是默认的重试处理：请求三次
		httpClient.getParams().setBooleanParameter("http.protocol.expect-continue", false);

		// 接收处理结果
		String result = null;
		try {
			// 执行Http Post请求
			httpClient.executeMethod(postMethod);

			// 返回处理结果
			result = postMethod.getResponseBodyAsString();
			LogUtils.debug(result);
		} catch (HttpException e) {
			// 发生致命的异常，可能是协议不对或者返回的内容有问题
			System.out.println("请检查输入的URL!");
			e.printStackTrace();
		} catch (IOException e) {
			// 发生网络异常
			System.out.println("发生网络异常!");
			e.printStackTrace();
		} finally {
			// 释放链接
			postMethod.releaseConnection();

			// 关闭HttpClient实例
			if (httpClient != null) {
				((SimpleHttpConnectionManager) httpClient.getHttpConnectionManager()).shutdown();
				httpClient = null;
			}
		}
		return result;
	}

	/**
	 * HttpClient 模拟GET请求 方法说明
	 * 
	 * @Discription:扩展说明
	 * @param url
	 * @param params
	 * @return String
	 * @Author: feizi
	 * @Date: 2015年4月17日 下午7:15:28
	 * @ModifyUser：feizi
	 * @ModifyDate: 2015年4月17日 下午7:15:28
	 */
	public static String getRequest(String url, Map<String, String> params) {
		// 构造HttpClient实例
		HttpClient client = new HttpClient();

		// 拼接参数
		String paramStr = "";
		for (String key : params.keySet()) {
			paramStr = paramStr + "&" + key + "=" + params.get(key);
		}
		paramStr = paramStr.substring(1);

		// 创建GET方法的实例
		GetMethod method = new GetMethod(url + "?" + paramStr);

		// 接收返回结果
		String result = null;
		try {
			// 执行HTTP GET方法请求
			client.executeMethod(method);

			// 返回处理结果
			result = method.getResponseBodyAsString();
		} catch (HttpException e) {
			// 发生致命的异常，可能是协议不对或者返回的内容有问题
			System.out.println("请检查输入的URL!");
			e.printStackTrace();
		} catch (IOException e) {
			// 发生网络异常
			System.out.println("发生网络异常!");
			e.printStackTrace();
		} finally {
			// 释放链接
			method.releaseConnection();

			// 关闭HttpClient实例
			if (client != null) {
				((SimpleHttpConnectionManager) client.getHttpConnectionManager()).shutdown();
				client = null;
			}
		}
		return result;
	}

	public static String doGet(String getUrl) throws Exception {
		org.apache.http.client.HttpClient client = HttpClients.createDefault();
		HttpGet get = new HttpGet(getUrl);
		HttpResponse response = client.execute(get);
		HttpEntity entity = response.getEntity();
		String result = EntityUtils.toString(entity, "UTF-8");
		get.releaseConnection();
		client = null;
		return result;
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static String doPost(String url, Map<String, String> params, String charset) {
		HttpPost httpPost = null;
		String result = null;
		try {
			httpPost = new HttpPost(url);
			List<NameValuePair> list = new ArrayList<NameValuePair>();
			Iterator iterator = params.entrySet().iterator();
			while (iterator.hasNext()) {
				Entry<String, String> elem = (Entry<String, String>) iterator.next();
				list.add(new BasicNameValuePair(elem.getKey(), elem.getValue()));
			}
			if (list.size() > 0) {
				UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, charset);
				httpPost.setEntity(entity);
			}
			HttpResponse response = httpClient.execute(httpPost);
			if (response != null) {
				HttpEntity resEntity = response.getEntity();
				if (resEntity != null) {
					result = EntityUtils.toString(resEntity, charset);
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return result;
	}

	public static String doPost(String url, String jsonstr, String charset) {
		HttpPost httpPost = null;
		String result = null;
		try {
			httpPost = new HttpPost(url);
			httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
			StringEntity se = new StringEntity(jsonstr, Charset.forName("utf-8"));
			se.setContentType("text/json");
			se.setContentEncoding(new BasicHeader("Content-Type", "application/json;charset=utf-8"));
			httpPost.setEntity(se);
			HttpResponse response = httpClient.execute(httpPost);
			if (response != null) {
				HttpEntity resEntity = response.getEntity();
				if (resEntity != null) {
					result = EntityUtils.toString(resEntity, charset);
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return result;
	}
}
